<template>
  <div class="scores-management">
    <!-- 搜索和过滤区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form" >
        <el-form-item label="学期" >
          <el-select v-model="filterForm.semester" placeholder="选择学期">
            <el-option
                v-for="item in semester"
                :key="item.v"
                :label="item.label"
                :value="item.v"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" >
          <el-select v-model="filterForm.class" placeholder="选择班级">
            <el-option
                label="全部班级"
                :value="0"
            />
            <el-option
                v-for="item in tea_classes"
                :key="item.classId"
                :label="item.name"
                :value="item.classId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程">
          <el-select v-model="filterForm.course" placeholder="选择课程">
            <el-option
                label="全部课程"
                :value="0"
            />
            <el-option
                v-for="item in tea_courses"
                :key="item.courseId"
                :label="item.name"
                :value="item.courseId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学号">
          <el-input v-model="filterForm.stuId" placeholder="输入学号" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <h3>成绩列表</h3>
            <el-tag type="info">共 {{ scores.length }} 条记录</el-tag>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="handleBatchImport">
              <el-icon><Upload /></el-icon>批量导入
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>导出成绩
            </el-button>
            <el-button type="warning" @click="handleBatchEdit" :disabled="!selectedRows.length">
              <el-icon><Edit /></el-icon>批量编辑
            </el-button>
          </div>
        </div>
      </template>

      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
      >
        <el-table-column type="selection"/>
        <el-table-column prop="stuId" label="学号"  sortable/>
        <el-table-column prop="stuName" label="姓名" width="100"/>
        <el-table-column prop="className" label="班级"/>
        <el-table-column prop="courseName" label="课程"/>
        <el-table-column prop="semester" label="学期">
          <template #default="scope">
            <el-tag type="primary">
              {{getSemesterLabel(scope.row.semester)}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="课程性质" width="100">
          <template #default="scope">
            <el-tag :type="getExamTypeTag(scope.row.type)">
              {{scope.row.type}}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="tempScore" label="成绩" width="70">
          <template #default="scope">
            <span :class="getScoreClass(scope.row.tempScore)">{{ scope.row.tempScore }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="score" label="最终成绩" width="120" sortable>
          <template #default="scope">
            <span :class="getScoreClass(scope.row.score)">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="成绩状态">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{getStatusLabel(scope.row.status)}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="70" >
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status === '1' || scope.row.status === '2'">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="scores.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑成绩对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'edit' ? '编辑成绩' : '批量编辑成绩'"
        width="500px"
    >
      <el-form
          ref="scoreFormRef"
          :model="scoreForm"
          :rules="scoreRules"
          label-width="100px"
      >
        <template v-if="dialogType === 'edit'">
          <el-form-item label="学号" prop="stuId">
            <el-input v-model="scoreForm.stuId" disabled />
          </el-form-item>
          <el-form-item label="姓名" prop="stuName">
            <el-input v-model="scoreForm.stuName" disabled />
          </el-form-item>
          <el-form-item label="课程号" prop="classId">
            <el-input v-model="scoreForm.courseId" disabled />
          </el-form-item>
          <!-- 添加课程名称显示 -->
          <el-form-item label="课程">
            <el-input v-model="scoreForm.courseName" disabled />
          </el-form-item>
          <el-form-item label="状态">
            <el-input v-model="scoreForm.status" disabled />
          </el-form-item>
        </template>

        <el-form-item label="成绩" prop="score">
          <el-input-number
              v-model="scoreForm.score"

              :max="100"
              :precision="1"
              :step="0.5"
              style="width: 180px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitScore" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed} from 'vue'
import { ElMessage} from 'element-plus'
import { Upload, Download, Edit } from '@element-plus/icons-vue'
import { useTeacherStores } from "@/stores/teacherStores.js";
import { storeToRefs } from "pinia";
import axios from "axios";
import baseURL from "@/config/config.js";
const { tea_classes, tea_courses, scores} = storeToRefs(useTeacherStores())
const { updateStudentScore  } = useTeacherStores()
// const scores = ref([])
// 过滤表单
const filterForm = reactive({
  class: 0,
  course: 0,
  semester: 0,
  stuId: ''
})
// 表格数据
const loading = ref(false)
const currentPage = ref(1) // 当前页
const pageSize = ref(10) // 一页表格的展示数量
const selectedRows = ref([])
const semester = [
  {label: '全部学期', v: 0},
  {label: '一年级第一学期', v: 1},
  {label: '一年级第二学期', v: 2},
  {label: '二年级第一学期', v: 3},
  {label: '二年级第二学期', v: 4},
  {label: '三年级第一学期', v: 5},
  {label: '三年级第二学期', v: 6},
  {label: '四年级第一学期', v: 7},
  {label: '四年级第二学期', v: 8},
]

function getSemesterLabel(id) {
  return semester.find(item => item.v === id).label
}
// 计算属性：分页后的数据
const tableData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return scores.value.slice(startIndex, endIndex)
})

// 编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('edit') // 'edit' 或 'batch'
const submitting = ref(false)
const scoreFormRef = ref(null)

const scoreForm = reactive({
  stuId: '',
  stuName: '',
  courseName: '',
  courseId: '',
  score: 0,
  status: '0'
})
const scoreRules = {
  score: [
    { required: true, message: '请输入成绩', trigger: 'blur' },
    { type: 'number', message: '成绩必须为数字', trigger: 'blur' }
  ]
}

// 处理搜索
const handleSearch = () => {
  loading.value = true

  axios({
    url: baseURL + '/score/get-score-by-conditions',
    params: {
      classId: filterForm.class,
      courseId: filterForm.course,
      semester: filterForm.semester,
      studentId: filterForm.stuId,
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    }
  }).then(res => {
    console.log("分数：" , res.data.data)
    currentPage.value = 1 // 重置到第一页
    scores.value = res.data.data

  }).finally(
      loading.value = false
  )
}

// 重置表单
const resetForm = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  handleSearch()
}

// 处理表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
}
const handleCurrentChange = (val) => {
  console.log("下一页", val)
  currentPage.value = val
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(scoreForm, row)
  dialogVisible.value = true
}

// 处理批量编辑
const handleBatchEdit = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要编辑的记录')
    return
  }
  dialogType.value = 'batch'
  scoreForm.score = 0
  scoreForm.remark = ''
  dialogVisible.value = true
}

// 处理批量导入
const handleBatchImport = () => {
  // TODO: 实现批量导入逻辑
}

// 处理导出
const handleExport = () => {
  axios({
    url: baseURL + '/score/download',
    params: {
      classId: filterForm.class,
      courseId: filterForm.course,
      semester: filterForm.semester,
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    responseType: 'blob',
  }).then(res => {
    handleDownload(res.data)
  })
}
// 处理文件下载的辅助函数
const handleDownload = (blobData) => {
  if (!blobData) return;

  // 1. 创建Blob对象（指定正确的MIME类型）
  const blob = new Blob([blobData], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // Excel文件类型
    // 若导出CSV，改为：type: 'text/csv'
  });

  // 2. 创建临时URL
  const url = URL.createObjectURL(blob);

  // 3. 创建下载链接
  const a = document.createElement('a');
  a.href = url;

  // 4. 设置文件名（可从响应头获取或固定）
  a.download = '成绩表.xlsx'; // 固定文件名
  // 或从响应头获取（如果后端返回）：
  // a.download = getFilenameFromHeader(response.headers);

  // 5. 触发下载
  document.body.appendChild(a);
  a.click();

  // 6. 释放资源
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};
// 提交成绩
const submitScore = () => {
  console.log("新分数" ,scoreForm)
  axios({
    url: baseURL + '/score/submit-student-score',
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('token')}`,
      'content-type': 'application/json'
    },
    data: {
      studentId: scoreForm.stuId,
      courseId: scoreForm.courseId,
      newScore: scoreForm.score,
      status: '1',
    }
  }).then((res) => {
    console.log(res)
    dialogVisible.value = false
    updateStudentScore(scoreForm.stuId, scoreForm.courseId, scoreForm.score)
    ElMessage.success("提交成功")
  }).catch(err => {
    console.log(err)
    ElMessage({
      type: 'error',
      message: '提交出错了:' + err.response.data.message,
    })
  })
}

// 获取考试类型标签
const getExamTypeTag = (type) => {
  const map = {
    '专业选修': 'warning',
    '专业必修': 'danger',
    '通识选修': 'info'
  }
  return map[type] || 'info'
}
// 获取考试类型标签
const getStatusTag = (type) => {
  const map = {
    '0': 'info',
    '1': 'warning',
    '2': 'success',
    '3': 'danger'
  }
  return map[type] || 'info'
}

const getStatusLabel = (type) => {
  const map = {
    '0': '成绩未提交',
    '1': '审核中',
    '2': '审核通过',
    '3': '成绩被拒绝'
  }
  return map[type] || type
}
// 获取成绩样式
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}
</script>
<style scoped>
.scores-management {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
/* 让表单元素平均分布 */
.filter-form .el-form-item {
  flex: 1;
  min-width: 200px; /* 防止元素过窄 */
  margin-right: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title h3 {
  margin: 0;
  font-size: 16px;
  color: #1f2937;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.el-button:focus:not(.is-focus):not(:active) {
  outline: none;
  box-shadow: none;
}
.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #e6a23c;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>